package networklogic

import (
	"context"

	"go-zero-admin/apps/modules/iot/cmd/link/network"
	"go-zero-admin/apps/modules/iot/cmd/link/network/constant"
	"go-zero-admin/apps/modules/iot/cmd/rpc/internal/svc"
	"go-zero-admin/apps/modules/iot/cmd/rpc/iotpb"
	"go-zero-admin/apps/modules/iot/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type DelNetWorkLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDelNetWorkLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelNetWorkLogic {
	return &DelNetWorkLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DelNetWorkLogic) DelNetWork(in *iotpb.DelNetWorkReq) (*iotpb.DelNetWorkResp, error) {
	// 先判断出每一个组件的状态，如果状态是已启动，则不让删除
	var networkList []*model.IotNetwork
	for _, v := range in.GetIds() {
		// 查询数据
		one, err := l.svcCtx.IotNetworkModel.FindOne(l.ctx, v)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
				tool.GetErrMsgFormat("delete network"), err, in)
		}

		// 判断是否已经启动
		if one.State == constant.NetworkStateClose {
			networkList = append(networkList, one)
			continue
		}

		return nil, errors.Wrapf(xerr.NewErrMsg("删除网络组件失败：ID："+
			convertor.ToString(one.Id)+"，名称："+one.Name+"，已启动，请关闭后再删除"),
			tool.GetErrMsgFormat("delete network"),
			"network id: "+convertor.ToString(one.Id)+", name: "+one.Name+", is opened", in)
	}

	// 删除数据
	err := l.svcCtx.IotNetworkModel.DeleteEx(l.ctx, nil, in.GetIds(), in.GetIsDel(), in.GetUpdateUser())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("delete network"), err, in)
	}

	// 删除network store中的数据 不报错，无需使用事务
	for _, v := range networkList {
		/// 启动或者关闭网络组件
		iNetworkType := new(network.NetworkType)
		networkType := iNetworkType.Of(v.Type)

		// reload网络组件
		network.INetworkManager.Destroy(networkType, v.Id)
	}

	return &iotpb.DelNetWorkResp{}, nil
}
